package lunchy.data.classes;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import lunchy.data.interfaces.ILunchyOrder;
import lunchy.data.interfaces.ILunchyOrderDAO;
import lunchy.data.interfaces.ILunchyOrderItem;

public class CLunchyXMLOrderDAO implements ILunchyOrderDAO
{
	private Document data;
	
	public CLunchyXMLOrderDAO(Document data)
	{
		this.data = data;
	}

	public void addOrder(ILunchyOrder orderToSave)
	{
		List<ILunchyOrderItem> orderItems = orderToSave.getOrderList();
		
		Node rootNode = data.getFirstChild();
		
		Element orderElement = data.createElement("order");
		
		orderElement.setAttribute("userId", orderToSave.getUserOrder().getId().toString());
		
		for (ILunchyOrderItem orderItem : orderItems)
		{
			Element orderItemElement = data.createElement("item");
			orderItemElement.setAttribute("id", orderItem.getItem().getId().toString());
			orderItemElement.setAttribute("count", orderItem.getCount().toString());
			orderElement.appendChild(orderItemElement);
		}
		
		rootNode.appendChild(orderElement);
		
		try
		{
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(data);
			StreamResult result = new StreamResult(new File("data/orders.xml"));
			transformer.transform(source, result);
		}
		catch (TransformerConfigurationException e)
		{
			e.printStackTrace();
		}
		catch (TransformerException e)
		{
			e.printStackTrace();
		}
	}
}
